<template>
    <el-form
        :inline="true"
        ref="searchFormRef"
        style="max-width: 100%"
        label-width="auto"
        :model="queryConditions"
        class="demo-ruleForm"
        status-icon
    >
        <el-form-item label="客户编码" prop="code">
            <el-input
                v-model="queryConditions.code"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-form-item label="客户名称" prop="name">
            <el-input
                v-model="queryConditions.name"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-form-item label="客户手机号" prop="phoneNum">
            <el-input
                v-model="queryConditions.phoneNum"
                style="width: 200px"
                size="large"
                placeholder="请输入"
                :suffix-icon="Search"
                clearable
            />
        </el-form-item>
        <el-button type="primary" :icon="Search" @click="search">查询</el-button>
        <el-button type="primary" :icon="RefreshRight" @click="resetForm">重置</el-button>
    </el-form>
    <TestPage
        :table-data="formattedTableData"
        :columns="tableColumns"
        :current-page="pageNo"
        :total="allPage"
        :page-size="pageSize"
        @page-change="handlePageChange"
        @action="handleTableAction"
        @edit="handleEditAction"
        @delete="handleDeleteAction"
    />
</template>

<script setup lang="ts">
import TestPage from "@/test/TestPage.vue"
import { Search, RefreshRight } from '@element-plus/icons-vue'
import { ref, computed, reactive, nextTick } from 'vue';
import { ElMessageBox, ElMessage, type FormInstance } from 'element-plus'
import type { Customer } from '@/types/public-xs/Customer';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();

let pageNo = ref(1)
let pageSize = ref(3)
let allPage = ref(0)

// 查询条件
const queryConditions = reactive({
    code: '',
    name: '',
    phoneNum: ''
})

const tableColumns = ref([
    { prop: 'id', label: '序号' },
    { prop: 'code', label: '客户编码' },
    { prop: 'name', label: '客户名称' },
    { prop: 'area', label: '客户业务地区' },
    { prop: 'address', label: '客户地址' },
    { prop: 'phoneNum', label: '手机号' },
    { prop: 'money', label: '交易' },
])

let tableData = ref<Customer[]>([])
// 计算属性
const formattedTableData = computed(() => {
    return tableData.value.map(item => ({
        ...item,
    }));
});

const handlePageChange = (newPage: number) => {
    pageNo.value = newPage
    fetchData(newPage)
}

const handleTableAction = (actionName: string) => {
    console.log('触发操作:', actionName)
    if (actionName === 'add') {
        router.push('/home/basic/new-customer/add'); // 跳转到新增页面
    }
}

const handleEditAction = (customer: Customer) => {
    router.push(`/home/basic/new-customer/edit/${customer.id}`); // 跳转到编辑页面
};

const handleDeleteAction = async (customer: Customer) => {
    try {
        await ElMessageBox.confirm('确定删除此客户？此操作不可恢复。', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        await axios.post(`http://localhost:8083/Customer/deleteCustomer?id=${customer.id}`);
        ElMessage.success('删除成功');
        await fetchData(pageNo.value); // 刷新
    } catch (error) {
        ElMessage.error('删除失败，请稍后重试');
        console.error('删除失败:', error);
    }
};

const searchFormRef = ref<FormInstance>()

// 查询
const search = () => {
    pageNo.value = 1; // 重置到第一页
    fetchData(1);
};

// 重置表单
const resetForm = () => {
    if (!searchFormRef.value) return;
    nextTick(() => {
        searchFormRef.value!.resetFields();
        pageNo.value = 1;
        fetchData(1);
    });
};

async function fetchData(page: number) {
    try {
        let response = await axios.post('http://localhost:8083/Customer/selectCustomerByPage', {
            pageNo: page,
            pageSize: pageSize.value,
            code: queryConditions.code,
            name: queryConditions.name,
            phoneNum: queryConditions.phoneNum
        });
        tableData.value = response.data.data.list;
        allPage.value = response.data.data.total;
        console.log(response.data);
    } catch (error) {
        ElMessage.error('获取客户数据失败');
        tableData.value = [];
        allPage.value = 0;
        console.error('获取数据失败:', error);
    }
}

fetchData(1)
</script>

<style scoped>
.demo-ruleForm {
    padding: 16px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
